package com.jzit168.library_utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Build
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer

/**
 *@Desc: 网络监听工具
 *@Author: Android Developer
 *@Date: 2020/10/14
 *
 **/
object NetworkUtil {
    private const val TAG = "NetworkUtil"

    private val conn = MutableLiveData<Boolean>()

    /**
     * 注册监听网络连接
     * @see hasConn 监听网络是否连接
     */
    fun register(context: Context) {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork
        if (network == null) {
            //无网络
            conn.postValue(false)
        } else {
            //有网络
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                connectivityManager.registerDefaultNetworkCallback(object :
                    ConnectivityManager.NetworkCallback() {

                    override fun onLost(network: Network) {
                        super.onLost(network)
                        conn.postValue(false)
                        Log.d(TAG, "onLost: 网络状态丢失")
                    }

                    override fun onAvailable(network: Network) {
                        super.onAvailable(network)
                        conn.postValue(true)
                        Log.d(TAG, "onAvailable: 网络状态已连接")
                    }
                }
                )
                Log.d(TAG, "check: 7.0及以上注册监听")
            } else {
                val request = NetworkRequest.Builder().build()
                connectivityManager.registerNetworkCallback(
                    request,
                    object : ConnectivityManager.NetworkCallback() {

                        override fun onLost(network: Network) {
                            super.onLost(network)
                            conn.postValue(false)
                            Log.d(TAG, "onLost: 网络状态丢失")
                        }

                        override fun onAvailable(network: Network) {
                            super.onAvailable(network)
                            conn.postValue(true)
                            Log.d(TAG, "onAvailable: 网络状态已连接")
                        }
                    }
                )
                Log.d(TAG, "check: 7.0一下注册监听")
            }
        }
    }

    fun hasConn(lifecycleOwner: LifecycleOwner, observer: Observer<Boolean>) {
        conn.observe(lifecycleOwner, observer)
    }
}